/**
 * Vue实例
 */
function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) { return pair[1]; }
    }
    return (false);
}
const app = new Vue({
    el: '#app',
    data() {
        return {
            map: undefined,
            icons: undefined,
            intervalId: -1,
            stopMarkerList: [], // 公交站点列表
            busMarkerList: [] // 正在运行的公交列表
        }
    },
    async mounted() {
        /**
         * leaflet地图
         */
        const cityMap = {
            wuhan: {
                center: [30.564035, 114.291801],
                zoom: 11
            }
        }
        const map = L.map('map', cityMap.wuhan)
        this.map = map

        // 图标
        const icons = {
            bus_stop: L.icon({
                iconUrl: './img/bus-stop.png',
                iconSize: [30, 35],
                iconAnchor: [15, 35],
                popupAnchor: [0, -35],
            }),
            bus_in_stop: L.icon({
                iconUrl: './img/bus-in-stop.png',
                iconSize: [30, 35],
                iconAnchor: [15, 35],
                popupAnchor: [0, -35],
            }),
            bus_running: L.icon({
                iconUrl: './img/bus-running.png',
                iconSize: [30, 35],
                iconAnchor: [15, 35],
                popupAnchor: [0, -35],
            }),
        }
        this.icons = icons

        // 初始化图层
        const apiUrlTemp = (nodeNum, serv_type, layr_type) => `http://t${nodeNum}.tianditu.gov.cn/${serv_type}/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=${layr_type}&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=44776aff3da7d82e777065fd48ab2da3`
            // 底图
        const imgLayr = L.tileLayer(apiUrlTemp(parseInt(Math.random() * 7), 'img_w', 'img')) // 卫星影像
        const vecLayr = L.tileLayer(apiUrlTemp(parseInt(Math.random() * 7), 'vec_w', 'vec')) // 矢量底图
        const terLayr = L.tileLayer(apiUrlTemp(parseInt(Math.random() * 7), 'ter_w', 'ter')) // 地形晕渲图
            // 注记
        const cvaLayr = L.tileLayer(apiUrlTemp(parseInt(Math.random() * 7), 'cva_w', 'cva')) // 矢量注记
        const ciaLayr = L.tileLayer(apiUrlTemp(parseInt(Math.random() * 7), 'cia_w', 'cia')) // 影像注记
        const ctaLayr = L.tileLayer(apiUrlTemp(parseInt(Math.random() * 7), 'cta_w', 'cta')) // 地形注记
        const iboLayr = L.tileLayer(apiUrlTemp(parseInt(Math.random() * 7), 'ibo_w', 'ibo')) // 全球境界
        const evaLayr = L.tileLayer(apiUrlTemp(parseInt(Math.random() * 7), 'eva_w', 'eva')) // 矢量英文注记
        const eiaLayr = L.tileLayer(apiUrlTemp(parseInt(Math.random() * 7), 'eia_w', 'eia')) // 影像英文注记

        // 添加基本图层
        vecLayr.addTo(map)
        cvaLayr.addTo(map)

        // 设置切换图层控件
        let baseMaps = {
            '矢量底图': vecLayr,
            '卫星影像底图': imgLayr,
            '地形晕渲图': terLayr
        }
        let overlayMaps = {
            '矢量注记': cvaLayr,
            '影像注记': ciaLayr,
            '地形注记': ctaLayr,
            '全球境界': iboLayr,
            '矢量英文注记': evaLayr,
            '影像英文注记': eiaLayr,
        }
        L.control.layers(baseMaps, overlayMaps, {
            position: 'topright'
        }).addTo(map)

        // 地图点击事件
        map.on('click', (e) => {
            console.log(`zoom: ${map.getZoom()}, latlng: ${e.latlng}`)
        })

        // busid
        const busid = getQueryVariable("bus");
        if (busid) {
            this.trackBuses(`027-${busid}`);
        }
    },
    methods: {
        async getRealTimeBus(busId) {
            try {
                let r = await axios.get(`http://bus.wuhancloud.cn:9087/website//web/420100/line/${busId}.do?Type=LineDetail`);
                if (r.status == 200) {
                    console.log(r.data.data)
                    return r.data.data
                } else {
                    throw r.status
                }
            } catch (e) {
                console.error(e)
                return {}
            }
        },
        /**
         * 更新公交的 marker 到 busMarkerList
         * @param {Array} buses 公交列表
         * @param {Array} stops 站点列表
         */
        async updateBuses(buses, stops) {
            const map = this.map
            const icons = this.icons
            const busMarkerList = this.busMarkerList
            buses.forEach(b => {
                if (b) {
                    b = b.split('|')
                    let inStop = (b[3] == '1')
                    let coord = coordtransform.gcj02towgs84(b[4], b[5])
                    let lng = coord[0]
                    let lat = coord[1]

                    // 遍历新的buses数组
                    // 找到之前的标记，如果存在则更新位置
                    // 若不存在则添加
                    let busMarkId = busMarkerList.findIndex(m => m.options.title == b[0])
                    let date = new Date()
                    let popupIcon = inStop ? icons.bus_in_stop : icons.bus_running
                    let popupContent = `<h5 style="margin:0">公交编号：${b[0]}</h5>
                        <p>${inStop ? '已到站' : '行驶中，下一站'}[${stops.find(s => s.stopOrder == b[2]).stopName}]</p>
                        <p>时间：${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}</p>`
                    if (busMarkId != -1) {
                        busMarkerList[busMarkId].setIcon(popupIcon)
                        busMarkerList[busMarkId].setPopupContent(popupContent)
                        busMarkerList[busMarkId].setLatLng(L.latLng(lat, lng))
                    } else {
                        busMarkerList.push(
                            L.marker([lat, lng], {
                                title: b[0],
                                icon: popupIcon
                            }).bindPopup(popupContent).addTo(map)
                        )
                    }
                }
            })
        },
        async trackBuses(busId) {
            const map = this.map
            const busMarkerList = this.busMarkerList
            let busData = await this.getRealTimeBus(busId)

            let { stops, buses, startStopName, endStopName } = busData

            if (startStopName && endStopName) {
                alert(`起始站：${startStopName}\n终点站：${endStopName}`);
            } else {
                return alert("线路信息不完整，请检查参数");
            }

            // 公交站
            let minLat, minLng, maxLat, maxLng
            minLat = minLng = 9999
            maxLat = maxLng = 0
            for (let i = 0; i < stops.length; i++) {
                if (stops[i].lat && stops[i].lng) {
                    if (stops[i].lat < 180 && stops[i].lng < 180) {
                        let coord = coordtransform.gcj02towgs84(stops[i].lng, stops[i].lat)

                        if (coord[1] > maxLat) maxLat = coord[1]
                        if (coord[0] > maxLng) maxLng = coord[0]
                        if (coord[1] < minLat) minLat = coord[1]
                        if (coord[0] < minLng) minLng = coord[0]

                        this.stopMarkerList.push(
                            L.marker([coord[1], coord[0]]).addTo(map)
                            .bindPopup(`<h5 style="margin:0">站名：${stops[i].stopName}</h5>\n序号：${stops[i].stopOrder}(${stops[i].stopId})`)
                        )
                    }
                }
            }
            // 缩放到公交站范围内
            map.fitBounds(L.latLngBounds(L.latLng(minLat, minLng), L.latLng(maxLat, maxLng)))

            // 实时跟踪公交位置
            this.updateBuses(buses, stops)
            const intervalPerMS = 5000
            this.intervalId = setInterval(async() => {
                buses = (await this.getRealTimeBus(busId)).buses

                this.updateBuses(buses, stops)

                // 遍历图中公交车数组，若不在buses中，说明不在线上了
                for (let i = 0; i < busMarkerList.length; i++) {
                    let isDriving = false
                    for (let j = 0; j < buses.length; j++) {
                        if (busMarkerList[i].options.title == buses[j].split('|')[0]) {
                            isDriving = true
                            break
                        }
                    }

                    if (!isDriving) {
                        busMarkerList[i].remove()
                        busMarkerList.splice(i, 1)
                        i--
                    }
                }
            }, intervalPerMS)
        },
        async stopTrack() {
            if (this.intervalId != -1) {
                clearInterval(this.intervalId)
            }
            this.intervalId = -1

            // 站点信息
            this.stopMarkerList.forEach(s => {
                s.remove()
            })

            // 车辆信息
            this.busMarkerList.forEach(b => {
                b.remove()
            })
        }
    }
})